#include <stdio.h>
#include <stdlib.h>
#include "list.h"

list * list_create()
{
	list * new = malloc(sizeof(list));
	if(new == NULL)
		return NULL;
	new->next = NULL;	
	return new;
}

//按位置插入方式,插到第i个结点之后
int list_insert_at(list *p,int i,datatype *data)
{
	if(i < 0)
		return -1;
	int j = 0;
	list * current = p;
	while(j < i && current != NULL)
	{
		current = current->next;
		j++;
	}
	if(current)
	{
		list *newnode = malloc(sizeof(*newnode));
		if(newnode == NULL)    
			return -2;
		newnode->data = *data;
		newnode->next = current->next;  //newnode在node之后
		current->next = newnode;
		return 1;
	}
	else	
		return -3;
}

void list_display(list * p)
{
	if (p == NULL)     //链表未创建的情况
		return;
	list *current = p->next;
	while(current != NULL)
	{
		printf("%d  ",current->data);
		current = current->next;
	}
	putchar('\n');
}

//按大小顺序插入方式
int list_order_insert(list *p,datatype *data)
{
	if (p == NULL)     //链表未创建的情况
		return -2;
	list * node = p,*current;
	while (node->next && node->next->data < *data)
		node = node->next;
	current = malloc(sizeof(*current));
	if(current == NULL)
		return -1;
	current->data = *data;
	current->next = node->next;
	node->next = current;
	return 1;
}
//删除第i个元素
int list_delete_at(list *p,int i,datatype *data)
{
	if (i <= 0)
		return -1;
	list * current = p;
	int j = 1;
	while (j++ < i && current)
		current = current->next;
	if (current)
	{
		list *ptr = current->next;   //要删除的元素
		*data = ptr->data;
		current->next = current->next->next;
		free(ptr);
		return 0;
	}
	else
		return -2;
}

int list_delete(list *p,datatype *data)
{
	if (p == NULL)     //链表未创建的情况
		return -2;
	list * current = p;
	while (current->next != NULL && current->next->data != *data)
		current = current->next;
	if(current->next == NULL)
		return -1;         //未找到需要删除的元素
	else
	{
		list *ptr = current->next;
		current->next = current->next->next;
		free(ptr);
	}
}

int list_isempty(list * p)
{
	if (p == NULL)     //链表未创建的情况
		return 1;
	return p->next == NULL;
}

void list_destory(list **p)
{
	list *current, *next;
	for (current = (*p)->next; current != NULL; current = next)
	{
		next = current->next;
		free(current);
	}
	free(*p);
	*p = NULL;
}
//按位置删除
//int list_delete_at(list *p,int i,datatype *data)
//{
//	int j = 0;
//	list * node = p,*current;
//	*data = -1;
//	if (i < 0)
//		return 0;
//	while (j++ < i && node)
//		node = node->next;
//	if(node)
//	{
//		current = node->next;
//		node->next=current->next;
//		*data = current->data;
//		free(current);
//		current = NULL;
//		return 0;
//	}
//	else 
//	return -2;
//}
